extends KinematicBody2D

signal health_changed
signal ammo_changed
signal dead
signal shoot	#坦克发送信号，由主场景负责生成子弹
#signal give_me_trail

export (PackedScene) var Bullet
export (int) var max_speed = 140
export (float) var rotation_speed = 3
export (float) var gun_cooldown = 0.5
export (int) var max_health = 50
export (int) var gun_shots = 1 #每一次射击的子弹数
export (float, 0, 1.5) var gun_spread = 0.2 #子弹的扩散程度
export (int) var max_ammo = 30
export (int) var ammo = -1	setget set_ammo #-1代表无限弹药
export (float) var offroad_friction = 0.75 #非道路地面速度衰减

var velocity = Vector2()
var can_shoot = true
var alive = true
var health:int
var map: TileMap  #tilemap的引用

func _ready():
	call_deferred("set_health", max_health)
	call_deferred("set_ammo", ammo)
	$GunTimer.wait_time = gun_cooldown
	$AnimationPlayer.play("init")
	
	for n in get_tree().root.get_children():
		#自动连接到主场景的子弹生成处理函数
		var flag = false
		if n.has_method("_on_Tank_shoot"):
			connect("shoot", n, "_on_Tank_shoot")
			flag = true
		#向主场景注册轨迹生成
		if n.has_method("_give_tank_trail"):
			n._give_tank_trail(self)
			flag = true
		if flag: break

func control(_delta):
	pass
	
func explode():
	alive = false
	set_deferred("$CollisionShape2D.disabled", true)
	$Body.hide()
	$Turret.hide()
	$Explosion.show()
	$Explosion.play()
	
func take_damage(amount):
	set_health(health - amount)
	if health <= 0:
		emit_signal("dead")
		explode()

func heal(amount):
	if not health < max_health: return
	set_health(health + amount)
	
func add_ammo(amount):
	set_ammo(ammo + amount)
	
func set_ammo(value):
	ammo = min(value, max_ammo)
	emit_signal("ammo_changed", 100 * ammo / max_ammo)
	
func set_health(value):
	health = min(value, max_health)
	var val = 100 * health / max_health
	emit_signal("health_changed", val)
	$Smoke.emitting = true if val < 30 else false
	
func shoot(num, spread, target = null):
	if can_shoot and ammo != 0:
		set_ammo(ammo - 1)
		can_shoot = false
		$GunTimer.start()
		var dir = Vector2.RIGHT.rotated($Turret.global_rotation)
		if num > 1:
			for i in range(num):
				var a = -spread + i * (2 * spread) / (num - 1)
				emit_signal("shoot", Bullet, $Turret/Muzzle.global_position, dir.rotated(a), target)
		else:
			emit_signal("shoot", Bullet, $Turret/Muzzle.global_position, dir, target)
		$AnimationPlayer.play("muzzle_flash")

func _physics_process(delta):
	if not alive: return
	control(delta)
	if map:
		var tile = map.get_cellv(map.world_to_map(global_position))
		if tile in GLOBALS.slow_terrain:
			velocity *= offroad_friction
	velocity = move_and_slide(velocity)

func _on_GunTimer_timeout():
	can_shoot = true


func _on_Explosion_animation_finished():
	queue_free()
